﻿using Grand.Core;
using Grand.Core.Plugins;
using Grand.Services.Cms;
using Grand.Services.Configuration;
using Grand.Services.Localization;
using System;
using System.Collections.Generic;
using System.Threading.Tasks;

namespace Grand.Plugin.Widgets.FacebookPixel
{
    public class FacebookPixelPlugin : BasePlugin, IWidgetPlugin
    {
        private readonly FacebookPixelSettings _facebookPixelSettings;
        private readonly ISettingService _settingService;
        private readonly IWebHelper _webHelper;
        private readonly IServiceProvider _serviceProvider;

        public FacebookPixelPlugin(FacebookPixelSettings facebookPixelSettings,
            ISettingService settingService, IWebHelper webHelper, IServiceProvider serviceProvider)
        {
            _facebookPixelSettings = facebookPixelSettings;
            _settingService = settingService;
            _webHelper = webHelper;
            _serviceProvider = serviceProvider;
        }

        /// <summary>
        /// Gets a configuration page URL
        /// </summary>
        public override string GetConfigurationPageUrl()
        {
            return $"{_webHelper.GetStoreLocation()}Admin/WidgetsFacebookPixel/Configure";
        }       

        /// <summary>
        /// Gets widget zones where this widget should be rendered
        /// </summary>
        /// <returns>Widget zones</returns>
        public IList<string> GetWidgetZones()
        {
            return new List<string>
            {
                FacebookPixelWidgetZone.Page, FacebookPixelWidgetZone.AddToCart, FacebookPixelWidgetZone.OrderDetails
            };
        }

        public void GetPublicViewComponent(string widgetZone, out string viewComponentName)
        {
            viewComponentName = "WidgetsFacebookPixel";
        }

        public override async Task Install()
        {
            var settings = new FacebookPixelSettings {
                PixelId = "000000000000000",
                PixelScript = @"<!-- Facebook Pixel Code -->
                                    <script>
                                      !function(f,b,e,v,n,t,s)
                                      {if(f.fbq)return;n=f.fbq=function(){n.callMethod?
                                      n.callMethod.apply(n,arguments):n.queue.push(arguments)};
                                      if(!f._fbq)f._fbq=n;n.push=n;n.loaded=!0;n.version='2.0';
                                      n.queue=[];t=b.createElement(e);t.async=!0;
                                      t.src=v;s=b.getElementsByTagName(e)[0];
                                      s.parentNode.insertBefore(t,s)}(window, document,'script',
                                      'https://connect.facebook.net/en_US/fbevents.js');
                                      fbq('init', '{PIXELID}');
                                      fbq('track', 'PageView');
                                    </script>
                                    <noscript>
                                      <img height='1' width='1' style='display:none'
                                           src='https://www.facebook.com/tr?id={PIXELID}&ev=PageView&noscript=1'/>
                                    </noscript>
                                <!-- End Facebook Pixel Code -->",
                AddToCartScript = @"<script> fbq('track', 'AddToCart', {contents: [{ id: '{PRODUCTID}', quantity: {QTY} }], content_name: '{PRODUCTNAME}', content_type: 'product', value: {AMOUNT}, currency: '{CURRENCY}'}); </script>",
                DetailsOrderScript = @"<script> fbq('track', 'Purchase', {currency: '{CURRENCY}', value: {AMOUNT}}); </script>",

            };
            await _settingService.SaveSetting(settings);

            await this.AddOrUpdatePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.PixelId", "Pixel Id");
            await this.AddOrUpdatePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.PixelId.Hint", "Enter Facebook Pixel ID.");
            await this.AddOrUpdatePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.PixelScript", "Facebook Pixel Code");
            await this.AddOrUpdatePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.PixelScript.Hint", "Paste the facebook pixel code generated by Facebook here. {PIXELID} will be dynamically replaced.");
            await this.AddOrUpdatePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.AddToCartScript", "Facebook Event - Add to cart");
            await this.AddOrUpdatePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.AddToCartScript.Hint", "Paste the event add to cart pixel code. {PRODUCTNAME}, {PRODUCTID}, {QTY}, {AMOUNT}, {CURRENCY} will be dynamically replaced.");
            await this.AddOrUpdatePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.DetailsOrderScript", "Facebook Event - Purchase");
            await this.AddOrUpdatePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.DetailsOrderScript.Hint", "Paste the event purchase pixel code. {AMOUNT} and {CURRENCY} will be dynamically replaced.");
            
            await base.Install();
        }

        /// <summary>
        /// Uninstall plugin
        /// </summary>
        public override async Task Uninstall()
        {
            //settings
            await _settingService.DeleteSetting<FacebookPixelSettings>();

            //locales
            await this.DeletePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.PixelId");
            await this.DeletePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.PixelId.Hint");
            await this.DeletePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.PixelScript");
            await this.DeletePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.PixelScript.Hint");
            await this.DeletePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.AddToCartScript");
            await this.DeletePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.AddToCartScript.Hint");
            await this.DeletePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.DetailsOrderScript");
            await this.DeletePluginLocaleResource(_serviceProvider, "Plugins.Widgets.FacebookPixel.DetailsOrderScript.Hint");

            await base.Uninstall();
        }


    }
}
